package daniel.taotao.search.service.impl;

import java.io.IOException;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import daniel.taotao.common.pojo.SearchItem;
import daniel.taotao.common.pojo.SearchResult;
import daniel.taotao.common.utils.TaotaoResult;
import daniel.taotao.search.dao.SearchDao;
import daniel.taotao.search.mapper.SearchItemMapper;
import daniel.taotao.search.service.SearchItemService;
@Service
public class SearchItemServiceImpl implements SearchItemService{
	@Autowired
	private SearchDao searchDao;
	@Autowired
	private SearchItemMapper searchItemMapper;
	@Autowired
	private SolrServer solrServer;
	@Override
	public TaotaoResult importItemsToIndex() throws SolrServerException, IOException {
		List<SearchItem> itemList = searchItemMapper.getItemList();
		for (SearchItem searchItem : itemList) {
			SolrInputDocument document=new SolrInputDocument();
			document.addField("id", searchItem.getId());
			document.addField("item_title", searchItem.getTitle());
			document.addField("item_sell_point", searchItem.getSell_point());
			document.addField("item_price", searchItem.getPrice());
			document.addField("item_image", searchItem.getImage());
			document.addField("item_category_name", searchItem.getCategory_name());
			document.addField("item_desc", searchItem.getItem_desc());
			// 5、向索引库中添加文档。
			solrServer.add(document);

		}
		solrServer.commit();
		return TaotaoResult.ok();
	}
	@Override
	public SearchResult search(String queryString, int page, int rows) throws Exception {
		//根据查询条件拼装查询对象
				//创建一个SolrQuery对象
				SolrQuery query = new SolrQuery();
				//设置查询条件
				query.setQuery(queryString);
				//设置分页条件
				if (page < 1) page =1;
				query.setStart((page - 1) * rows);
				if (rows < 1) rows = 10;
				query.setRows(rows);
				//设置默认搜索域
				query.set("df", "item_title");
				//设置高亮显示
				query.setHighlight(true);
				query.addHighlightField("item_title");
				query.setHighlightSimplePre("<font color='red'>");
				query.setHighlightSimplePost("</font>");
				//调用dao执行查询
				SearchResult searchResult = searchDao.search(query);
				//计算查询结果的总页数
				long recordCount = searchResult.getRecordCount();
				long pages =  recordCount / rows;
				if (recordCount % rows > 0) {
					pages++;
				}
				searchResult.setTotalPages(pages);
				//返回结果
				return searchResult;
	
	}

}
